#define  _CRT_SECURE_NO_WARNINGS
#include"Queue.h"
void QueueInit(Que* pq)
{
	assert(pq);
	pq->head = pq->tail = NULL;
	pq->size = 0;
}


void QueueDestroy(Que* pq)
{
	assert(pq);
	QNode* cur = pq->head;
	while (cur)
	{
		QNode* next = cur->next;
		free(cur);
		cur = next;
	}
	pq->head = pq->tail = NULL;
	pq->size = 0;
}


void QueuePush(Que* pq,DataType x)
{
	assert(pq);
	QNode* newnode = (QNode*)malloc(sizeof(QNode));
	if (newnode == NULL)
	{
		perror("malloc");
		exit(-1);
	}
	newnode->data = x;
	newnode->next = NULL;
	if (pq->tail == NULL)
	{
		pq->head = pq->tail = newnode;
	}
	else
	{
		pq->tail->next = newnode;
		pq->tail = newnode;
	}
	pq->size++;
}

DataType QueueFront(Que* pq)
{
	assert(pq);
	assert(!QueueEmpty(pq));

	return pq->head->data;

}

void QueuePop(Que* pq)
{
	assert(pq);
	assert(!QueueEmpty(pq));
	if (pq->head->next == NULL)
	{
		free(pq->head);
		pq->head = pq->tail = NULL;
	}
	else
	{
		QNode* newnode = pq->head->next;
		free(pq->head);
		pq->head = newnode;
	}
	pq->size--;
}

DataType QueueBack(Que* pq)
{
	assert(pq);
	assert(!QueueEmpty(pq));

	return pq->tail->data;
}

bool QueueEmpty(Que* pq)
{
	assert(pq);
	return pq->head == NULL;
}

int QueueSize(Que* pq)
{
	assert(pq);
	return pq->size;
}


typedef struct {
	Que* q1;
	Que* q2;
} MyStack;


MyStack* myStackCreate() {
	MyStack* st = (MyStack*)malloc(sizeof(MyStack));
	QueueInit(st->q1);
	QueueInit(st->q2);
	return st;
}

void myStackPush(MyStack* st, int x) {
	if (!QueueEmpty(st->q1))
	{
		QueuePush(st->q1, x);
	}
	else
	{
		QueuePush(st->q2, x);
	}
}

int myStackPop(MyStack* st) {
	Que* empty = st->q1;
	Que* noempty = st->q2;
	if (!QueueEmpty(st->q1))
	{
		noempty = st->q1;
		empty = st->q2;
	}
	while (QueueSize(noempty) > 1)
	{
		QueuePush(empty, QueueFront(noempty));
		QueuePop(noempty);
	}
	int top = QueueFront(noempty);
	QueuePop(noempty);
	return top;
}

int myStackTop(MyStack* st) {
	if (QueueEmpty(st->q1))
	{
		QueueBack(st->q1);
	}
	else
	{
		QueueBack(st->q2);
	}

}

bool myStackEmpty(MyStack* st) {
	return QueueEmpty(st->q1) && QueueEmpty(st->q2);

}

void myStackFree(MyStack* st) {
	QueueDestroy(st->q1);
	QueueDestroy(st->q2);
	free(st);
}
